<?php
namespace app\Admin\controller;
use app\Admin\model\Advert as AdvertModel;
use app\admin\controller\Base;

class Advert extends Base
{
    public function index()
    {
        $advert = new advertModel();
        if(request()->isPost()){
            $sorts=input('post.');

            foreach ($sorts as $k => $v) {
                $advert->update(['id'=>$k,'sort'=>$v]);
            }
            $this->success('更新排序成功！',url('index'));
            return;
        }
        $advertres=$advert->order('sort desc')->paginate(3);
        $this->assign('list',$advertres);
        return view();
    }

    public function add()
    {   
        /*echo 123;
        die;*/
        if(request()->isPost()){
            $data=input('post.');
            $data['addtime']=time();
            $validate = \think\Loader::validate('advert');
            if(!$validate->scene('add')->check($data)){
                $this->error($validate->getError());
                die();
            }
            $advert = new AdvertModel;
            if($advert->save($data)){
                $this->success('添加广告成功',url('index'));
            }else{
                $this->error('添加广告失败！');
            }
            return;
        }
        return view();
    }

    public function edit(){
        $id=input('id');
        $advert = db('advert')->find($id);
        // var_dump($advert);
        // die();
        if(request()->isPost()){
            $data = [
                'id'=>input('id'),
                'title'=>input('title'),
                'url'=>input('url'),
                'desc'=>input('desc'),
            ];
            $validate = \think\Loader::validate('advert');
            if(!$validate->scene('edit')->check($data)){
               $this->error($validate->getError()); 
               die();
            }
            $advert = new AdvertModel;
            if($advert->update($data)){
                $this->success('修改广告成功！','index');
            }else{
                $this->error('修改广告失败！');
            }
            return;
        }
        $this->assign('advert',$advert);
        return $this->fetch();
    }

    public function del(){
        $id=input('id');
        if(db('advert')->delete(input('id'))){
            $this->success('删除广告成功！','index');
        }else{
            $this->error('删除广告失败！');
        }
        
    }



}
